package com.huluobo.koltinim2003a.contract.login

import com.huluobo.koltinim2003a.adapter.EMCallbackAdapter
import com.huluobo.koltinim2003a.extention.isValidPassword
import com.huluobo.koltinim2003a.extention.isValidUserName
import com.hyphenate.chat.EMClient

/**
 * Created by lc on 2022/9/21.
 */
class LoginPresenter(val view: LoginContract.View) : LoginContract.Presenter {
    override fun login(userName: String, password: String) {
        //1.验证用户名是否合法
        if (userName.isValidUserName()) {
            //2.验证密码是否合法
            if (password.isValidPassword()) {
                //3.开始触发登录进度条
                view.onStartLogin()
                //4.登录到环信,让环信去触发登录成功或者失败
                loginEaseMob(userName, password)
            } else view.onPasswordError()
        } else view.onUserNameError()
    }

    private fun loginEaseMob(userName: String, password: String) {
        EMClient.getInstance().login(userName, password, object : EMCallbackAdapter() {
            override fun onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups()//如果登录成功获取所有的群组
                EMClient.getInstance().chatManager().loadAllConversations()//获取所有会话列表
                //ANR 主线程超过5秒没有响应,或者动作(点击或者触摸)超过10秒没有相应
                runOnUIThread {
                    view.onLoggedInSuccess()
                }
            }

            override fun onError(code: Int, error: String?) {
                runOnUIThread {
                    view.onLoggedInFailed(error)
                }
            }
        })
    }
}